document.addEventListener('DOMContentLoaded', function() {
    const addButtonLast = document.querySelector('#add-button-last');
    const addButtonFirst = document.querySelector('#add-button-first');
    const clearButton = document.querySelector('#clear-button');
    const addWorkflowButton = document.querySelector('#add-workflow-button');
    const undoButton = document.querySelector('#undo-button');
    const newSelectElement = document.createElement('select');
    newSelectElement.className = 'column-select';
    newSelectElement.innerHTML = `
    <option value="none">-选择任务-</option>
    <option value="invalid">未成功获取能够融合的任务列表</option>
    `;
    const secondColumn = document.querySelector('.top-half .column:nth-child(2)');
    secondColumn.innerHTML = '';
    secondColumn.appendChild(newSelectElement.cloneNode(true));
    secondColumn.firstChild.disabled = false;
    let currentColumnCapacity = 3;
    let fuseOrder = [];
    let actionHistory = [];
    let currentValidTasks = [];
    let current_task = null;
    let currentTaskHistory = [];
    let status = 'task';
    let typeInputTimer = null;
    let activeColumnIndex = 1;
    let workflow_sigs = [];
    let input_file_content = null;
    getTaskList(activeColumnIndex);
    const topHalf = document.querySelector('.top-half');
    function updateColumnWidth() {
        const newWidth = `${100 / (currentColumnCapacity)}vw`;
        for (let i = 0; i < topHalf.children.length; i++) {
            topHalf.children[i].style.width = newWidth;
        }
    }
    function findEmptyColumnFirst() {
        const firstColumn = topHalf.children[0];
        if (!firstColumn.hasChildNodes()) {
            return firstColumn;
        }
        return null;
    }
    function findEmptyColumnLast() {
        const lastColumn = topHalf.children[topHalf.children.length - 1];
        if (!lastColumn.hasChildNodes()) {
            return lastColumn;
        }
        return null;
    }
    function prependNewColumn() {
        const newColumn = document.createElement('div');
        newColumn.className = 'column';
        newColumn.innerHTML = ''
        newColumn.appendChild(newSelectElement.cloneNode(true));
        newColumn.firstChild.disabled = false
        topHalf.insertBefore(newColumn, topHalf.children[0]);
        currentColumnCapacity++;
        updateColumnWidth();
        for (let i = 0; i < fuseOrder.length; i++) {
            fuseOrder[i]++
        }
        return newColumn;
    }
    function appendNewColumn() {
        const newColumn = document.createElement('div');
        newColumn.className = 'column';
        newColumn.innerHTML = ''
        newColumn.appendChild(newSelectElement.cloneNode(true));
        newColumn.firstChild.disabled = false
        topHalf.appendChild(newColumn);
        currentColumnCapacity++;
        updateColumnWidth();
        return newColumn;
    }
    addButtonFirst.addEventListener('click', function() {
        if (status === 'task') {
            alert('请先选择任务')
            return
        }
        let targetColumn = findEmptyColumnFirst();
        if (!targetColumn) {
            targetColumn = prependNewColumn();
            actionHistory.push(["prependColumn", 1])
        } else {
            targetColumn.appendChild(newSelectElement.cloneNode(true))
            targetColumn.firstChild.disabled = false
            actionHistory.push(["prependColumn", 0])
        }
        // select = targetColumn.firstChild;
        status = 'task'
        activeColumnIndex = 0;
        getTaskList(activeColumnIndex);
    });
    addButtonLast.addEventListener('click', function() {
        if (status === 'task') {
            alert('请先选择任务')
            return
        }
        let targetColumn = findEmptyColumnLast();
        if (!targetColumn) {
            targetColumn = appendNewColumn();
            actionHistory.push(["appendColumn", 1])
        } else {
            targetColumn.appendChild(newSelectElement.cloneNode(true))
            targetColumn.firstChild.disabled = false
            actionHistory.push(["appendColumn", 0])
        }
        status = 'task'
        activeColumnIndex = currentColumnCapacity - 1;
        getTaskList(activeColumnIndex);
    });
    undoButton.addEventListener('click', function() {
        if (actionHistory.length === 0) {
            alert('已退回到原始状态')
            return
        }
        let lastAction = actionHistory.pop()
        if (lastAction[0] === "prependColumn") {
            if (lastAction[1] === 1) {
                topHalf.removeChild(topHalf.children[0])
                currentColumnCapacity--
                for (let i = 0; i < fuseOrder.length; i++) {
                    fuseOrder[i]--
                }
            } else {
                topHalf.children[0].innerHTML = ''
            }
            status = 'fuse'
        }
        else if (lastAction[0] === "appendColumn") {
            if (lastAction[1] === 1) {
                topHalf.removeChild(topHalf.children[currentColumnCapacity - 1])
                currentColumnCapacity--
            } else {
                topHalf.children[currentColumnCapacity - 1].innerHTML = ''
            }
            status = 'fuse'
        }
        else if (lastAction[0] === "setTask") {
            let columnIndex = lastAction[1]
            topHalf.children[columnIndex].firstChild.selectedIndex = 0
            topHalf.children[columnIndex].firstChild.disabled = false
            activeColumnIndex = columnIndex;
            status = 'task'
            fuseOrder.pop()
            current_task = currentTaskHistory.pop()
            updateTypeLabels()
        }
    })
    function debounceTypeUpdate() {
        if (typeInputTimer) {
            clearTimeout(typeInputTimer);
        }
        typeInputTimer = setTimeout(() => {
            if (status === 'task') {
                getTaskList(activeColumnIndex);
            }
        }, 500);
    }
    document.getElementById('input-itype').addEventListener('input', function() {
        validateInput(this, 'error-itype');
        debounceTypeUpdate();
    });
    document.getElementById('input-otype').addEventListener('input', function() {
        validateInput(this, 'error-otype');
        debounceTypeUpdate();
    });
    function validateInput(inputElement, errorElementId) {
        const value = inputElement.value;
        const isValid = value.length === 0 || tsvalidate(value);
        const errorElement = document.getElementById(errorElementId);
        
        if (!isValid) {
            inputElement.classList.add('error');
            errorElement.style.display = 'block';
        } else {
            inputElement.classList.remove('error');
            errorElement.style.display = 'none';
        }
    }
    clearButton.addEventListener('click', function() {
        actionHistory = [];
        fuseOrder = [];
        current_task = null;
        updateTypeLabels();
        topHalf.innerHTML = `
        <div class="column"></div>
        <div class="column"></div>
        <div class="column"></div>
        `;
        const secondColumn = document.querySelector('.top-half .column:nth-child(2)');
        secondColumn.innerHTML = '';
        secondColumn.appendChild(newSelectElement.cloneNode(true));
        secondColumn.firstChild.disabled = false
        currentColumnCapacity = 3;
        updateColumnWidth();
        activeColumnIndex = 1;
        getTaskList(activeColumnIndex);
        status = 'task'
    });
    document.querySelector('.top-half').addEventListener('change', function(e) {
        if (e.target.tagName === 'SELECT') {
            currentTaskHistory.push(current_task);
            for (each of currentValidTasks) {
                if (each.name === e.target.value) {
                    current_task = each.fused
                    break
                }
            }
            actionHistory.push(["setTask", activeColumnIndex]);
            fuseOrder.push(activeColumnIndex);
            updateTypeLabels();
            status = 'fuse'
            e.target.disabled = true
        }
    });
    function updateTypeLabels() {
        fused = current_task;
        if (fused) {
            fused = fused.replace(' ','')
            let [fused_name, rest] = fused.split(':')
            let [it, ot] = rest.split('->')
            document.getElementById('current-itype-label').textContent = it;
            document.getElementById('current-otype-label').textContent = ot;
            document.getElementById('current-task-name').textContent = fused_name
        } else {
            document.getElementById('current-itype-label').textContent = '无';
            document.getElementById('current-otype-label').textContent = '无';
            document.getElementById('current-task-name').textContent = '无'
        }
    }
    addWorkflowButton.addEventListener('click', function() {
        if (fuseOrder.length < 1) {
            alert('请至少选择一个任务');
            return;
        }
        let workflow_name = getWorkflowName()
        if (!workflow_name) {
            alert('请输入工作流名称');
            return;
        }
        if (workflow_sigs.find(sig => sig.name === workflow_name)) {
            alert('工作流名称已存在');
            return;
        }
        let taskNames = [];
        let fuseParams = [];
        for (let i = 0; i < fuseOrder.length; i++) {
            taskNames.push(topHalf.children[fuseOrder[i]].firstChild.value);
            if (i === 0) {
                fuseParams.push([true, false]);
            } else {
                if (fuseOrder[i] > fuseOrder[i - 1]) {
                    fuseParams.push([true, false]);
                } else {
                    fuseParams.push([false, false]);
                }
            }
        }
        let itype = document.getElementById('current-itype-label').textContent;
        let otype = document.getElementById('current-otype-label').textContent;
        const workflowData = {
            task_names: taskNames,
            fuse_params: fuseParams,
            task_sig: `${workflow_name}:${itype}->${otype}`
        };
        fetch('/_/workflows/add_workflow', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(workflowData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('工作流添加成功');
                clearButton.click();
                getWorkflowList();
            } else {
                alert('工作流添加失败: ' + data.error);
            }
        })
        .catch(error => {
            console.error('添加工作流失败:', error);
            alert('添加工作流失败，请重试');
        });
    });
    function getTaskList(currentColumnIndex) {
        let ibound = null;
        let obound = null;
        if (currentColumnIndex === 0) {
            let itype = document.getElementById('input-itype').value;
            if (!itype || !tsvalidate(itype)) {
                ibound = null;
            } else {
                ibound = "input_task:Void->" + itype;
            }
            obound = current_task
        } else if (currentColumnIndex === 1) {
            let itype = document.getElementById('input-itype').value;
            let otype = document.getElementById('input-otype').value;
            if (!itype || !tsvalidate(itype)) {
                ibound = null;
            } else {
                ibound = "input_task:Void->" + itype;
            }
            if (!otype || !tsvalidate(otype)) {
                obound = null;
            } else {
                obound = "output_task:" + otype + "->Void";
            }
        }
        else { // currentColumnIndex == currentColumnCapacity - 1
            let otype = document.getElementById('input-otype').value;
            if (!otype || !tsvalidate(otype)) {
                obound = null;
            } else {
                obound = "output_task:" + otype + "->Void";
            }
            ibound = current_task
        }
        if (ibound) {
            ibound = ibound.replace(' ', '');
        }
        if (obound) {
            obound = obound.replace(' ', '');
        }
        const requestBody = {
            ibound: ibound,
            obound: obound,
            force: false,
            ifix: false,
            ofix: false
        };
        fetch('/_/workflows/valid_tasks', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestBody)
        })
        .then(response => response.json())
        .then(data => { // [name, sig, fused]
            const currentColumn = topHalf.children[currentColumnIndex];
            const select = currentColumn.querySelector('select');
            select.innerHTML = '<option value="none">-选择任务-</option>';
            currentValidTasks = []
            data["tasks"].forEach(([name, sig, fused]) => {
                const option = document.createElement('option');
                option.value = name;
                option.textContent = sig;
                select.appendChild(option);
                let task = {
                    "name": name,
                    "sig": sig,
                    "fused": fused
                }
                currentValidTasks.push(task)
            });
        })
        .catch(error => {
            console.error('获取任务列表失败:', error);
            alert('获取任务列表失败，请重试');
        });
    }
    function getWorkflowList() {
        fetch('/_/workflows/all', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            const workflowList = document.querySelector('.workflow-list');
            workflowList.innerHTML = '';
            workflow_sigs = data.workflow_sigs;
            if (workflow_sigs && workflow_sigs.length > 0) {
                const table = document.createElement('table');
                table.className = 'workflow-table';
                const thead = document.createElement('thead');
                thead.innerHTML = `
                    <tr>
                        <th>工作流名称</th>
                        <th>输入类型</th>
                        <th>输出类型</th>
                        <th>输入文件</th>
                        <th>操作</th>
                    </tr>
                `;
                table.appendChild(thead);
                const tbody = document.createElement('tbody');
                workflow_sigs.forEach(workflow => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${workflow.name}</td>
                        <td>${workflow.input_type}</td>
                        <td>${workflow.output_type}</td>
                        <td>
                            <input type="file" id="file-input-${workflow.name}" style="display: none;">
                            <button class="select-file" data-workflow="${workflow.name}">选择文件</button>
                            <span id="file-name-${workflow.name}" class="file-name"></span>
                        </td>
                        <td>
                            <button class="start-workflow" data-name="${workflow.name}">启动</button>
                            <button class="delete-workflow" data-name="${workflow.name}">删除</button>
                        </td>
                    `;
                    tbody.appendChild(tr);
                });
                table.appendChild(tbody);
                workflowList.appendChild(table);
                
                document.querySelectorAll('.select-file').forEach(button => {
                    button.addEventListener('click', function() {
                        const workflowName = this.getAttribute('data-workflow');
                        selectFile(workflowName);
                    });
                });

                document.querySelectorAll('input[type="file"]').forEach(input => {
                    input.addEventListener('change', function(event) {
                        const workflowName = this.id.replace('file-input-', '');
                        handleFileSelect(event, workflowName);
                    });
                });
                
                document.querySelectorAll('.start-workflow').forEach(button => {
                    button.addEventListener('click', function() {
                        const workflowName = this.getAttribute('data-name');
                        startWorkflow(workflowName);
                    });
                });
                
                document.querySelectorAll('.delete-workflow').forEach(button => {
                    button.addEventListener('click', function() {
                        const workflowName = this.getAttribute('data-name');
                        deleteWorkflow(workflowName);
                    });
                });
            } else {
                workflowList.innerHTML = '<p class="no-workflows">暂无工作流</p>';
            }
        })
        .catch(error => {
            console.error('获取工作流列表失败:', error);
            alert('获取工作流列表失败，请重试');
        });
    }
    function deleteWorkflow(workflowName) {
        if (confirm('确定要删除这个工作流吗？')) {
            fetch(`/_/workflows/delete/${workflowName}`, {
                method: 'DELETE',
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    getWorkflowList();
                } else {
                    alert('工作流删除失败: ' + data.error);
                }
            })
            .catch(error => {
                console.error('删除工作流失败:', error);
                alert('删除工作流失败，请重试');
            });
        }
    }
    function selectFile(workflowName) {
        const fileInput = document.getElementById(`file-input-${workflowName}`);
        fileInput.click();
    }
    function handleFileSelect(event, workflowName) {
        const file = event.target.files[0];
        if (!file) {
            return;
        }
        readFileContent(file).then(content => {
            input_file_content = content;
            const fileNameSpan = document.getElementById(`file-name-${workflowName}`);
            fileNameSpan.textContent = file.name;
        }).catch(error => {
            alert('读取文件失败: ' + error.message);
        });
        event.target.value = ''; // 清空文件输入框，允许重复选择同一文件
    }
    function readFileContent(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => resolve(e.target.result);
            reader.onerror = (e) => reject(new Error('文件读取失败'));
            reader.readAsText(file);
        });
    }
    function startWorkflow(workflowName) {
        const workflow = workflow_sigs.find(w => w.name === workflowName);
        if (workflow.input_type !== 'Void' && !input_file_content) {
            alert('请上传输入文件');
            return;
        }
        fetch(`/_/workflows/start`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                workflow_name: workflowName,
                input_file_content: input_file_content
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('工作流启动成功');
            } else {
                alert('工作流启动失败: ' + data.error);
            }
        })
        .catch(error => {
            console.error('启动工作流失败:', error);
            alert('启动工作流失败，请重试');
        });
    }
    function getWorkflowName() {
        const workflowName = document.getElementById('workflow-name').value.trim();
        if (!workflowName) {
            document.getElementById('error-workflow-name').style.display = 'block';
            return null;
        }
        document.getElementById('error-workflow-name').style.display = 'none';
        return workflowName;
    }
    getWorkflowList();
});


// 修改添加工作流的函数
async function addWorkflow() {
    const workflowName = getWorkflowName();
    if (!workflowName) return;

    const workflowData = {
        name: workflowName,
        stages: getStagesData(),
        input_type: document.getElementById('input-itype').value,
        output_type: document.getElementById('input-otype').value
    };

    try {
        const response = await fetch('/api/workflows', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(workflowData)
        });

        if (response.ok) {
            alert('工作流添加成功！');
            loadWorkflows(); // 重新加载工作流列表
            clearWorkflow(); // 清空当前工作流
        } else {
            alert('添加工作流失败！');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('添加工作流时发生错误！');
    }
}

// 修改删除工作流的函数
async function deleteWorkflow(workflowName) {
    if (!confirm(`确定要删除工作流 "${workflowName}" 吗？`)) {
        return;
    }

    try {
        const response = await fetch(`/api/workflows/${encodeURIComponent(workflowName)}`, {
            method: 'DELETE'
        });

        if (response.ok) {
            alert('工作流删除成功！');
            loadWorkflows(); // 重新加载工作流列表
        } else {
            alert('删除工作流失败！');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('删除工作流时发生错误！');
    }
}

// 修改清空工作流的函数
function clearWorkflow() {
    // ... existing clear logic ...
    document.getElementById('workflow-name').value = '';
    document.getElementById('error-workflow-name').style.display = 'none';
}